max_attempts = 3
--进入录音播报超时时间
timeout = 10000
--最长录音时间
max_record_seconds = 300
digit_timeout = 5000
api = freeswitch.API()
core_server_ip = api:executeString("eval $${core_service_ip}")
local_ip_v4 = api:executeString("eval $${local_ip_v4}")
json = require "json"

account_user = session:getVariable("destination_number")
caller_id_number = session:getVariable("caller_id_number")
filename = "/usr/local/freeswitch/recordings/voicemai-" .. session:getVariable("destination_number") .. "_" ..  session:getVariable("caller_id_number") .. "_" .. os.date("%Y%m%d%H%M%S", os.time()) ..".wav"
freeswitch.consoleLog("INFO","account_user is "..account_user .."\n")
 --util functions below
local lan,greeting,macro = 'zh',nil,'voicemail_say_phone_number'

function setSoundPrefix()
	if not session:ready() then return end
    -- body
    local sound_prefix = "/usr/local/freeswitch/sounds/zh/cn/link/voicemail/yunpbx"
    if(lan == 'en') then
        sound_prefix = "/usr/local/freeswitch/sounds/en/us/callie/voicemail/yunpbx"
    end
    session:setVariable('sound_prefix',sound_prefix)
    freeswitch.consoleLog("INFO",'language is '.. lan ..' and filepath is '.. sound_prefix )
end
 function to_curl(section)
 	local handle = io.popen("curl -d section="..section.." -d station=" .. account_user  .." http://"..core_server_ip..":8080/switch/voicemail")
    local result = handle:read("*a")
    handle:close()
    session:consoleLog("INFO","get data => " .. result)
    if(result == '') then
        return {}
    else
      return json.decode(result)
    end
 end
 function get_greeting()
 	if not session:ready() then return end
 	local j = to_curl('info')
 	lan ,greeting = j.lan,j.greeting
 	if(lan == "en") then
 	 	macro = "voicemail_say_number" 
 	else
 		lan = 'zh'
 	end
 	setSoundPrefix()
 end
--录音结束行为
function afterRecordAction()
	-- body
	local j = to_curl('getnumber')
	local listened,new =  j[1] - j[2],j[2]
	new = tonumber(new) + 1
	local msg = new ..'/' .. listened 
	local event = freeswitch.Event("SWITCH_EVENT_MESSAGE_WAITING");
	event:addHeader("MWI-Messages-Waiting", "yes");
	event:addHeader("MWI-Message-Account", "user/"..account_user.."@"..local_ip_v4);
	event:addHeader("MWI-Voice-Message", msg);
	event:fire();
	freeswitch.consoleLog("INFO","message was fired to " .. account_user)
	--写数据
	os.execute("curl -d section=record -d station="..account_user 
		.. " -d caller_id_number="..caller_id_number 
		.. " -d filename='"..filename.."' http://" ..core_server_ip..":8080/switch/voicemail")
end
--录音
 function voice_record()
 	if not session:ready() then return end
 	get_greeting()
 	-- body
 	session:sleep(500)
 	if(greeting ~= 'null' and greeting ~= nil) then
 		session:streamFile(greeting)
 	else
 		session:streamFile('vm-extention.wav')
 		session:sayPhrase(macro, tonumber(account_user), lan)
 		session:streamFile('vm-cannot_listen.wav')
 	end

 	session:streamFile("vm-record_greeting.wav")
	session:sleep(1000)
	session:streamFile("tone_stream://%(1000,0,1000)")
	-- os.execute("mkdir -p " .. directory)
	if not session:ready() then 
		error("hang up before record" )
		return 
	else
		session:consoleLog("INFO","start recordFile " .. filename)
		-- session:setInputCallback('onInputCBF','')
		local t1 = os.time() 
		local r = session:recordFile(filename,max_record_seconds,30,10)
		local t2 = os.time() 
		-- session:unsetInputCallback()
		session:consoleLog("info", "session:recordFile() = " .. r )
		--录音之后
		if(t2 - t1 >= 5) then
			afterRecordAction()
		end
	end 
 end

---main process
 freeswitch.consoleLog("INFO","voicemail record app start!")
 session:setVariable("opbx_voicemail",'true')
 session:answer()
 -- voice_record()
 local result,err = pcall(voice_record)
	if(result == true) then
	    freeswitch.consoleLog('INFO','recording success') 
	else
	    freeswitch.consoleLog('INFO','get error:'..err) 
	end

